package io.github.talelin.sleeve.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.talelin.sleeve.common.exception.NotFoundException;
import io.github.talelin.sleeve.dto.BannerDTO;
import io.github.talelin.sleeve.entity.Banner;
import io.github.talelin.sleeve.mapper.BannerMapper;
import io.github.talelin.sleeve.service.BannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private BannerMapper bannerMapper;
    @Override
    public Page selectPage(Page page) {
        return bannerMapper.selectPage(page,null);
    }
    @Override
    public Banner selectById(Long id) {
        return bannerMapper.selectById(id);
    }

    @Override
    public void updateById(Long id, BannerDTO bannerDTO) {
        Banner oldBanner = bannerMapper.selectById(id);
        if(oldBanner ==null){
            throw new NotFoundException("banner查询不到,确认id是否正确");
        }
        BeanUtils.copyProperties(bannerDTO,oldBanner);//前者赋给后者
        bannerMapper.updateById(oldBanner);
    }
    @Override
    public void insertBanner(BannerDTO bannerDTO) {
        Banner newBanner = new Banner();
        BeanUtils.copyProperties(bannerDTO,newBanner);//前者赋给后者
        bannerMapper.insert(newBanner);
    }

    @Override
    public void deleteById(Long id) {
        Banner oldBanner = bannerMapper.selectById(id);
        if(oldBanner ==null){
            throw new NotFoundException("banner查询不到,确认id是否正确");
        }
        bannerMapper.deleteById(id);
    }

    @Override
    public Long getAllBanners() {
        // 设置redisTemplate对象key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Long sum = (Long) redisTemplate.opsForValue().get("sum");
        // 从redis缓存中获取总人数
        // 判断redis中是否存在数据
        if(sum == null){
            // 如果为空，就去数据库中进行查询
            sum = Long.valueOf(bannerMapper.getAllBanners().size());
            // 并且把查询到的数据放入大redis中
            redisTemplate.opsForValue().set("sum",sum,15, TimeUnit.SECONDS);
        }
        return sum;
    }
}
